import asyncio
from typing import List, Dict, Optional
from loguru import logger
from .api_client import BitgetAPIClient

class AssetManager:
    def __init__(self):
        self.api = BitgetAPIClient()
        
    async def __aenter__(self):
        await self.api.__aenter__()
        return self
        
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.api.__aexit__(exc_type, exc_val, exc_tb)
        
    async def batch_withdraw(self, coin: str, addresses: List[Dict], amount: float) -> List[Dict]:
        """批量提币"""
        results = []
        coin_info = await self.api.get_coin_info(coin)
        
        for address_info in addresses:
            try:
                # 验证最小提币量
                min_withdraw = float(coin_info["chains"][0]["minWithdrawAmount"])
                if amount < min_withdraw:
                    logger.warning(f"提币数量 {amount} 小于最小提币量 {min_withdraw}")
                    continue
                    
                # 计算手续费
                fee = float(coin_info["chains"][0]["withdrawFee"])
                total_amount = amount + fee
                
                # 执行提币
                result = await self.api.withdraw(
                    coin=coin,
                    address=address_info["address"],
                    amount=str(amount),
                    chain=address_info["chain"]
                )
                results.append({
                    "address": address_info["address"],
                    "status": "success",
                    "order_id": result["orderId"]
                })
                
            except Exception as e:
                logger.error(f"提币失败: {str(e)}")
                results.append({
                    "address": address_info["address"],
                    "status": "failed",
                    "error": str(e)
                })
                
        return results
        
    async def collect_assets(self, target_account: str) -> Dict:
        """资产归集"""
        results = {}
        assets = await self.api.get_subaccount_assets()
        
        for account in assets:
            if account["userId"] == target_account:
                continue
                
            for asset in account["assetsList"]:
                coin = asset["coin"]
                available = float(asset["available"])
                
                if available <= 0:
                    continue
                    
                try:
                    # 检查币种是否支持划转
                    coin_info = await self.api.get_coin_info(coin)
                    if not coin_info["transfer"]:
                        logger.warning(f"币种 {coin} 不支持划转")
                        continue
                        
                    # 执行划转
                    result = await self.api.transfer_assets(
                        from_user=account["userId"],
                        to_user=target_account,
                        coin=coin,
                        amount=str(available)
                    )
                    
                    if coin not in results:
                        results[coin] = []
                    results[coin].append({
                        "from": account["userId"],
                        "amount": available,
                        "status": "success",
                        "transfer_id": result["transferId"]
                    })
                    
                except Exception as e:
                    logger.error(f"划转失败: {str(e)}")
                    if coin not in results:
                        results[coin] = []
                    results[coin].append({
                        "from": account["userId"],
                        "amount": available,
                        "status": "failed",
                        "error": str(e)
                    })
                    
        return results
        
    async def liquidate_assets(self, target_coin: str = "USDT", slippage: float = 0.1) -> Dict:
        """自动清算"""
        results = {}
        assets = await self.api.get_subaccount_assets()
        
        # 获取目标币种的市场信息
        target_market = f"{target_coin}USDT"
        
        for account in assets:
            for asset in account["assetsList"]:
                coin = asset["coin"]
                available = float(asset["available"])
                
                if available <= 0 or coin == target_coin:
                    continue
                    
                try:
                    # 构建交易对
                    symbol = f"{coin}{target_coin}"
                    
                    # 获取当前市场价格
                    # 注意：这里需要实现获取市场价格的API
                    current_price = await self._get_market_price(symbol)
                    
                    # 计算考虑滑点的价格
                    price_with_slippage = current_price * (1 - slippage)
                    
                    # 执行卖出
                    result = await self.api.place_order(
                        symbol=symbol,
                        side="sell",
                        order_type="limit",
                        size=str(available),
                        price=str(price_with_slippage)
                    )
                    
                    if coin not in results:
                        results[coin] = []
                    results[coin].append({
                        "account": account["userId"],
                        "amount": available,
                        "price": price_with_slippage,
                        "status": "success",
                        "order_id": result["orderId"]
                    })
                    
                except Exception as e:
                    logger.error(f"清算失败: {str(e)}")
                    if coin not in results:
                        results[coin] = []
                    results[coin].append({
                        "account": account["userId"],
                        "amount": available,
                        "status": "failed",
                        "error": str(e)
                    })
                    
        return results
        
    async def _get_market_price(self, symbol: str) -> float:
        """获取市场价格"""
        # 这里需要实现获取市场价格的逻辑
        # 可以使用WebSocket或REST API
        pass 